/**
* Author:LSP
* Date:2020-12-24
*/
// @导入引用开发环境
if (typeof require === 'undefined') require = importModule
const { Base } = require("./lsp环境")

// @小组件配置
const widgetConfigs = {
    // 鸡精数据来源：1：第三方，2：天天基金
    sourceType: 2,
    // 直接指定鸡精id
    defaultFundId: '001838,002190,161725,160643,000336,161726,519019',
    // 是否是iPhone12mini
    isIphone12Mini: false,
    refreshInterval: 0, // 缓存刷新时间--估算(单位：分钟)
    // 预览模式：0：小尺寸，1：中等尺寸，2：大尺寸，负数：不预览
    previewMode: 1,

    selectPicBg: true, // 选择图片
    colorBgMode: false,  // 纯色背景模式
    bgColor: Color.black(), // 黑色背景

    // 鸡精名字体
    fundFont: new Font('Menlo', 11),
    // 鸡精净值字体
    fundExpectWorthFont: Font.boldSystemFont(12),
    // 鸡精日期字体
    fundDateFont: new Font('Menlo', 11),
    // 鸡精涨的字体颜色
    riseUpColor: new Color("EA4041", 0.8),
    // 鸡精跌的字体颜色
    fallDownColor: new Color("1BA784", 0.8),

    // 间距
    padding: {
        top: 10, // 上边距
        left: 10, // 左边距
        bottom: 10, // 底边距
        right: 2, // 右边距
    },

    // 鸡精调整scheme
    urlScheme: 'alipays://platformapi/startapp?appId=20000793',
}

// @定义小组件
class Widget extends Base {
    constructor(scriptName) {
        super(scriptName)
        // 初始化其他变量
        this.setSelectPicBg(widgetConfigs.selectPicBg)
        this.setColorBgMode(widgetConfigs.colorBgMode, widgetConfigs.bgColor)
        this.paddingSetting(Object.assign(widgetConfigs.padding))
        this.refreshIntervalTime(widgetConfigs.refreshInterval)
        this.setPreViewSizeMode(widgetConfigs.previewMode)
    }

    //-------------------------------------

    /**
     * 基金数据获取
     * @param {Array} fidArr 鸡精id数组
     */
    async getFund(fidArr) {
        let fundData = undefined
        if (widgetConfigs.sourceType == 1) {
            // 第三方鸡精实时数据
            fundData = await this.getThirdFund(fidArr)
        } else {
            // 天天鸡精实时数据
            fundData = await this.getTTFund(fidArr)
        }

        log(`实时数据：${JSON.stringify(fundData)}`)
        return fundData
    }

    /**
    * 第三方基金数据实时获取
    * @param {Array} fidArr 鸡精id数组
    */
    async getThirdFund(fidArr) {
        log(`>>>>>第三方鸡精数据获取<<<<<`)
        // 拼接基金id
        let fidFull = ''
        for (let fid of fidArr) {
            fidFull = fidFull + fid + ","
        }
        fidFull = fidFull.substring(0, fidFull.lastIndexOf(','))

        // 请求基金数据
        const url = `https://api.doctorxiong.club/v1/fund?code=${fidFull}`
        const fundResponse = await this.httpGet(url)
        const fundJsonData = fundResponse.data
        // 鸡精数据列表
        const fundDataArr = []
        for (const fund of fundJsonData) {
            // 鸡精数据
            const fundData = {}
            // 鸡精code
            fundData.code = fund.code
            // 鸡精名字
            fundData.name = fund.name
            // 鸡精估算值更新时间
            fundData.estimateDate = fund.expectWorthDate
            // 鸡精净值估算值
            fundData.estimate = fund.expectGrowth
            if (fund.expectWorthDate.search(fund.netWorthDate) != -1) {
                // 净值更新日期
                fundData.estimateDate = fund.netWorthDate
                // 净值
                fundData.estimate = fund.dayGrowth
            }
            fundDataArr.push(fundData)
        }

        return fundDataArr
    }


    /**
     * 天天基金数据实时获取
     * @param {Array} fidArr 鸡精id数组
     */
    async getTTFund(fidArr) {
        log(`>>>>>天天鸡精数据获取<<<<<`)
        // 当前日期
        const date = new Date()
        // 小时
        const hour = date.getHours()
        // 鸡精数据列表
        const fundDataArr = []
        for (const fid of fidArr) {
            // 鸡精数据
            const fundData = {}
            const jzUrl = `http://fundgz.1234567.com.cn/js/${fid}.js?rt=${Date.parse(new Date())}`
            const fundResponse = await this.httpGet(jzUrl, false)
            const fundJsonData = JSON.parse(fundResponse.replace('jsonpgz(', '').replace(');', ''))
            // 鸡精code
            fundData.code = fundJsonData.fundcode
            // 鸡精名字
            fundData.name = fundJsonData.name
            // 鸡精估算值更新时间
            fundData.estimateDate = fundJsonData.gztime
            // 鸡精净值估算值
            fundData.estimate = fundJsonData.gszzl
            // 七点后开始请求最后净值，看看是否更新了
            if (hour >= 19) {
                const jzUrl = `https://fundf10.eastmoney.com/F10DataApi.aspx?type=lsjz&code=${fid}`
                const jzData = await this.httpGet(jzUrl, false)
                // 日期正则
                var dateRgexp = /\d{4}-\d{2}-\d{2}/g
                const dateResult = jzData.match(dateRgexp)
                if (dateResult != null && dateResult.length > 0) {
                    const date = dateResult[0]
                    const currentDate = this.getDateStr('yyyy-MM-dd')
                    if (date == currentDate) {
                        log(`鸡精最终净值更新了~~`)
                        // 净值更新日期
                        fundData.estimateDate = date
                        // 净值正则
                        const jzRegexp = /-?\d+(\.\d+)?%/g
                        const jzResult = jzData.match(jzRegexp)
                        if (jzResult != null && jzResult.length > 0) {
                            // 净值
                            fundData.estimate = parseFloat(jzResult[0].slice(0, -1))
                        }
                    }
                }
            }

            fundDataArr.push(fundData)
        }

        return fundDataArr
    }

    //-------------------------------------

    /**
     * @渲染小组件
     */
    async render() {
        // 鸡精id数组
        const fidArr = widgetConfigs.defaultFundId.replace(/\，/g, ",").split(",")
        // 进行请求数据
        const fundData = await this.getFund(fidArr)
        // 数据排序
        const sortedFundData = fundData.sort(function (a, b) { return b.estimate - a.estimate })
        //-------------------------------------


        //-------------------------------------
        const widget = new ListWidget()
        //-------------------------------------
        let index = 0
        for (const fund of sortedFundData) {
            index = index + 1
            //创建水平方向stack
            const hStack = widget.addStack()
            hStack.layoutHorizontally()
            // 直接跳转支付宝基金页面
            hStack.url = widgetConfigs.urlScheme
            // 颜色值
            const estimate = fund.estimate // 当前基金单位净值估算日涨幅
            let fundColor = widgetConfigs.riseUpColor
            if (estimate < 0) {
                fundColor = widgetConfigs.fallDownColor
            }

            // 基金名称
            const title = hStack.addText(`>› ${fund.name}`)
            title.font = widgetConfigs.fundFont
            title.textColor = fundColor
            title.lineLimit = 1

            // 净值
            hStack.addSpacer(5)
            const expectWorth = hStack.addText(`‹ ${estimate} ›`)
            expectWorth.font = widgetConfigs.fundExpectWorthFont
            expectWorth.textColor = fundColor
            expectWorth.lineLimit = 1

            // 净值估算更新日期
            hStack.addSpacer(5)
            const expectWorthDate = hStack.addText(`${fund.estimateDate.slice(0, 16)}`)
            expectWorthDate.font = widgetConfigs.fundDateFont
            expectWorthDate.textColor = fundColor
            expectWorthDate.lineLimit = 1
            expectWorthDate.textOpacity = 0.9

            // 左对齐
            hStack.addSpacer()
            if (index != sortedFundData.length) {
                widget.addSpacer(5)
            }

        }
        //-------------------------------------


        //-------------------------------------
        return widget
        //-------------------------------------
    }
}

// @运行测试
const { Running } = require("./lsp环境")
await Running(Widget, Script.name())